 <template>
  <div class="favorite-list-container">
    <div class="header">
      <h2>收藏管理</h2>
      <div class="actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户或课程..."
          :prefix-icon="Search"
          clearable
          @clear="handleSearch"
          @input="handleSearch"
          class="search-input"
        />
        <el-button type="success" @click="refreshData">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="favoriteList"
      border
      style="width: 100%"
    >
      <el-table-column type="expand">
        <template #default="props">
          <div class="favorite-detail">
            <div class="detail-section">
              <h4>课程信息</h4>
              <div class="detail-item">
                <span class="label">课程标题：</span>
                <span>{{ props.row.course?.title }}</span>
              </div>
              <div class="detail-item" v-if="props.row.course?.subtitle">
                <span class="label">副标题：</span>
                <span>{{ props.row.course?.subtitle }}</span>
              </div>
              <div class="detail-item" v-if="props.row.course?.description">
                <span class="label">描述：</span>
                <span>{{ props.row.course?.description }}</span>
              </div>
              <div class="detail-item">
                <span class="label">课程链接：</span>
                <a :href="props.row.course?.courseUrl" target="_blank" class="link">{{ props.row.course?.courseUrl }}</a>
              </div>
            </div>
            
            <div class="detail-section">
              <h4>其他信息</h4>
              <div class="detail-grid">
                <div class="detail-item">
                  <span class="label">机构：</span>
                  <span>{{ props.row.course?.institution }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">难度：</span>
                  <el-tag :type="getDifficultyType(props.row.course?.difficulty)">
                    {{ props.row.course?.difficulty }}
                  </el-tag>
                </div>
                <div class="detail-item">
                  <span class="label">学科：</span>
                  <span>{{ props.row.course?.subject }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">平台：</span>
                  <span>{{ props.row.course?.platform }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">用户名：</span>
                  <span>{{ props.row.username }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">收藏时间：</span>
                  <span>{{ formatDate(props.row.createdTime) }}</span>
                </div>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="课程封面" width="100">
        <template #default="{ row }">
          <el-image
            :src="row.course?.coverImage"
            fit="cover"
            class="course-cover"
            :preview-src-list="row.course?.coverImage ? [row.course.coverImage] : []"
          >
            <template #error>
              <div class="image-placeholder">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="course.title" label="课程标题" min-width="200" show-overflow-tooltip>
        <template #default="{ row }">
          <span>{{ row.course?.title }}</span>
          <el-link
            type="primary"
            :href="row.course?.courseUrl"
            target="_blank"
            class="external-link"
            :underline="false"
          >
            <el-icon class="link-icon"><Link /></el-icon>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="150" />
      <el-table-column prop="course.institution" label="机构" width="150" show-overflow-tooltip />
      <el-table-column prop="course.difficulty" label="难度" width="100">
        <template #default="{ row }">
          <el-tag :type="getDifficultyType(row.course?.difficulty)" v-if="row.course?.difficulty">
            {{ row.course?.difficulty }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="收藏时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="120">
        <template #default="{ row }">
          <el-button type="danger" @click="handleDelete(row)" :icon="Delete" size="small">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @update:current-page="currentPage = $event"
      @update:page-size="pageSize = $event"
      class="pagination"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Delete, Picture, Link, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 状态变量
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const favoriteList = ref([])

// 防抖函数
const debounce = (fn, delay) => {
  let timer = null
  return (...args) => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 获取收藏列表
const fetchFavorites = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      search: searchQuery.value
    }
    await request.get('/favorite/page', params, {
      showDefaultMsg: false,
      onSuccess: (res) => {
        favoriteList.value = res.records||[]
        total.value = res.total||0
      }
    })
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    ElMessage.error('获取收藏列表失败')
  } finally {
    loading.value = false
  }
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchFavorites()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchFavorites()
}

// 处理搜索
const handleSearch = debounce(() => {
  currentPage.value = 1
  fetchFavorites()
}, 300)

// 刷新数据
const refreshData = () => {
  fetchFavorites()
}

// 处理删除收藏
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该收藏记录吗？此操作不可恢复。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await request.delete(`/favorite/${row.id}`, {
        successMsg: '删除成功'
      })
      fetchFavorites()
    } catch (error) {
      console.error('删除收藏记录失败:', error)
    }
  })
}

// 获取难度标签类型
const getDifficultyType = (difficulty) => {
  switch (difficulty) {
    case '初级':
      return 'success'
    case '中级':
      return 'warning'
    case '高级':
      return 'danger'
    default:
      return 'info'
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '暂无'
  return new Date(date).toLocaleString()
}

// 初始化
onMounted(() => {
  fetchFavorites()
})
</script>

<style lang="scss" scoped>
.favorite-list-container {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 24px;
      color: var(--el-text-color-primary);
    }

    .actions {
      display: flex;
      gap: 10px;

      .search-input {
        width: 200px;
      }
    }
  }

  .course-cover {
    width: 60px;
    height: 60px;
    border-radius: 4px;
  }

  .image-placeholder {
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--el-fill-color-light);
    border-radius: 4px;
    color: var(--el-text-color-secondary);
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.favorite-detail {
  padding: 20px;
  background-color: #f9f9f9;
  
  .detail-section {
    margin-bottom: 20px;
    
    h4 {
      margin-top: 0;
      margin-bottom: 15px;
      color: var(--el-color-primary);
      font-weight: 600;
      border-bottom: 1px solid var(--el-border-color-light);
      padding-bottom: 8px;
    }
    
    .detail-item {
      margin-bottom: 10px;
      line-height: 1.5;
      
      .label {
        font-weight: 600;
        color: var(--el-text-color-regular);
        margin-right: 8px;
      }
      
      .link {
        color: var(--el-color-primary);
        text-decoration: none;
        
        &:hover {
          text-decoration: underline;
        }
      }
    }
    
    .detail-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 15px;
      
      @media (max-width: 768px) {
        grid-template-columns: repeat(2, 1fr);
      }
      
      @media (max-width: 480px) {
        grid-template-columns: 1fr;
      }
    }
  }
}

.external-link {
  margin-left: 8px;
  font-size: 16px;
  
  .link-icon {
    vertical-align: middle;
  }
}
</style>